import sys
import os
import time

import api

retry_interval = os.getenv('JIANMU_INTERVAL')
tag = os.getenv('JIANMU_TAG')
git_branch = os.getenv('JIANMU_GIT_BRANCH')
interval = 0


def check_retry_interval():
    if not retry_interval or retry_interval.isspace():
        print('error: retry_interval不能为空', flush=True)
        sys.exit(1)
    if not tag or tag.isspace():
        print('error: tag不能为空', flush=True)
        sys.exit(1)


def loop(trigger_id):
    i = 1
    while True:
        if i == 1:
            print('第' + str(i) + '次查询', end='', flush=True)
        else:
            print(flush=True)
            print('第' + str(i) + '次查询，间隔时间为' + retry_interval + 's',  end='', flush=True)
        # 查询构建计划状态
        workflow_instance = api.get_workflow_instance(trigger_id)
        status = workflow_instance.get('status')
        print(' 流程实例状态:', status)
        if status == 'SUSPENDED':
            print('error: 构建计划已挂起，请手动操作后重试', flush=True)
            sys.exit(1)
        elif status == 'FINISHED':
            print('success: 构建计划执行完成！', flush=True)
            break
        elif status == 'TERMINATED':
            print('error: 构建计划执行失败', flush=True)
            sys.exit(1)
        else:
            i = i + 1
            time.sleep(int(retry_interval))


def main():
    print(flush=True)
    check_retry_interval()
    api.check_param()
    # 获取构建计划
    build_plan = api.get_build_plan()
    # 修改构建计划标签
    build_plan['tagName'] = tag
    if git_branch and not git_branch.isspace():
        build_plan['branch'] = git_branch
    api.update_build_plan(build_plan)
    # 触发构建计划
    trigger_vo = api.trigger(build_plan.get('projectId'))
    print('info: 构建计划触发成功！', flush=True)
    print(flush=True)
    loop(trigger_vo.get('triggerId'))


if __name__ == "__main__":
    main()
